package com.ks.core.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
@Component
public class ShortUrl {

    /**
     * 新浪appKey
     */
    static String APPKEY = "4004876100";
    static String ACCESSTOKEN = "2.00yDWKCGoNDC4E978e783ad3Lum6iB";

    static String actionUrl = "http://api.t.sina.com.cn/short_url/shorten.json?source={source}&url_long={longUrl}";

    /**
     * 根据长连接获取短链接
     *
     * @param longUrl
     * @return
     */
    public static String getShortUrl(String longUrl) {
        if (ToolUtil.isEmpty(longUrl)) {
            return null;
        }
        String shortUrl = null;
        try {
            String url = actionUrl.replace("{source}", APPKEY).replace("{longUrl}", URLEncoder.encode(longUrl, "utf-8"));
            byte[] bytes = HttpUtil.doGet(url);
            JSONObject jsonObject = JSONObject.parseObject(new String(bytes));
            log.info("短链接响应：{}", jsonObject);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("urls"));
            JSONObject json = (JSONObject) jsonArray.get(0);
            if (json.getBoolean("result")) {
                shortUrl = json.getString("url_short");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("长链接编码异常：{}", longUrl);
        }
        return shortUrl;
    }

    public static void main(String[] args) {
        String url = "https://www.xiyitong.net/web/1111/index.html?isshare=1";
        String shortUrl = getShortUrl(url);
        System.out.println(shortUrl);
    }
}
